package com.course02.order_backend.exception.llh;

import com.course02.order_backend.entity.llh.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLTransientConnectionException;

//捕获全局异常
@RestControllerAdvice//捕获所有带有@RestController注解的Controller类
public class GlobalExceptionHandler {
    private  static final Logger log= (Logger) LoggerFactory.getLogger(GlobalExceptionHandler.class);
    //捕获自定义异常
    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException e){
        log.error("业务错误，错误码：{},描述：{}，详情：{}",e.getErrorCode().getCode(),e.getErrorCode().getMessage(),e.getDetail(),e);
        return Result.error(e.getErrorCode().getCode(),e.getErrorCode().getMessage());
    }
    //捕获数据库连接异常
    @ExceptionHandler(SQLTransientConnectionException.class)
    public Result<?> handleDbConnectError(SQLTransientConnectionException e){
        log.error("数据库连接失败",e);
        return Result.error(ErrorCode.DB_CONNECT_FAIL.getCode(),ErrorCode.DB_CONNECT_FAIL.getMessage());
    }
    //捕获系统异常
    @ExceptionHandler(Exception.class)
    public Result<?> handleSystemError(Exception e){
        log.error("系统错误",e);
        return Result.error(ErrorCode.SYSTEM_ERROR.getCode(),ErrorCode.SYSTEM_ERROR.getMessage());
    }

}
